<template>
  <div>
    <el-row>
      <el-col :span="6">
        <el-input
          placeholder="输入书名查找"
          v-model="page.bookName"
          maxlength="20"
          @change="search"
        >
          <!-- el-input中的@change事件是失去焦点或按下回车触发 -->
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button icon="el-icon-search" @click="search" type="success"
          >搜索
        </el-button>
      </el-col>
      <el-col :span="2">
        <el-button icon="el-icon-delete" @click="reset" type="info"
          >重置
        </el-button>
      </el-col>
      <el-col :span="3" :offset="11">
        <el-button type="warning" @click="dialogVisible1 = true">
          添加书籍
        </el-button>
      </el-col>
    </el-row>
    <el-table :data="bookList" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- 每一行 -->
          <el-row>
            <!-- 每一行两列第一列 -->
            <el-col :span="8" :offset="2">
              <!-- 各自那一列里面又分为一行两列 -->
              <el-row>
                <el-col :span="3">
                  <span class="title1">书籍id</span>
                </el-col>
                <el-col :span="12">
                  <span style="display: flex; padding-top: 2px">{{
                    scope.row.id
                  }}</span>
                </el-col>
              </el-row>
              <!-- 各自那一列里面又分为一行两列 -->
            </el-col>
            <!-- 每一行两列第一列 -->
            <!-- 每一行两列第二列 -->
            <el-col :span="8">
              <!-- 各自那一列里面又分为一行两列 -->
              <el-row>
                <el-col :span="4">
                  <span class="title1">书名</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ scope.row.bookName }}</span>
                </el-col>
              </el-row>
              <!-- 各自那一列里面又分为一行两列 -->
            </el-col>
            <!-- 每一行两列第二列 -->
          </el-row>
          <!-- 每一行-结束 -->
          <br />
          <!-- 每一行 -->
          <el-row>
            <!-- 每一行两列第一列 -->
            <el-col :span="8" :offset="2">
              <!-- 各自那一列里面又分为一行两列 -->
              <el-row>
                <el-col :span="3">
                  <span class="title1">作者</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ scope.row.author }}</span>
                </el-col>
              </el-row>
              <!-- 各自那一列里面又分为一行两列 -->
            </el-col>
            <!-- 每一行两列第一列 -->
            <!-- 每一行两列第二列 -->
            <el-col :span="8">
              <!-- 各自那一列里面又分为一行两列 -->
              <el-row>
                <el-col :span="4">
                  <span class="title1">分类</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ scope.row.className }}</span>
                </el-col>
              </el-row>
              <!-- 各自那一列里面又分为一行两列 -->
            </el-col>
            <!-- 每一行两列第二列 -->
          </el-row>
          <!-- 每一行结束 -->
          <br />
          <!-- 每一行 -->
          <el-row>
            <!-- 每一行两列第一列 -->
            <el-col :span="8" :offset="2">
              <!-- 各自那一列里面又分为一行两列 -->
              <el-row>
                <el-col :span="3">
                  <span class="title1">书号</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ scope.row.bookNo }}</span>
                </el-col>
              </el-row>
              <!-- 各自那一列里面又分为一行两列 -->
            </el-col>
            <!-- 每一行两列第一列 -->
            <!-- 每一行两列第二列 -->
            <el-col :span="8">
              <!-- 各自那一列里面又分为一行两列 -->
              <el-row>
                <el-col :span="4">
                  <span class="title1">价格</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ scope.row.price }}</span>
                </el-col>
              </el-row>
              <!-- 各自那一列里面又分为一行两列 -->
            </el-col>
            <!-- 每一行两列第二列 -->
          </el-row>
          <!-- 每一行结束 -->
          <br />
          <!-- 每一行 -->
          <el-row>
            <!-- 每一行两列第一列 -->
            <el-col :span="8" :offset="2">
              <!-- 各自那一列里面又分为一行两列 -->
              <el-row>
                <el-col :span="3">
                  <span class="title1">出版社</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ scope.row.publish }}</span>
                </el-col>
              </el-row>
              <!-- 各自那一列里面又分为一行两列 -->
            </el-col>
            <!-- 每一行两列第一列 -->
            <!-- 每一行两列第二列 -->
            <el-col :span="8">
              <!-- 各自那一列里面又分为一行两列 -->
              <el-row>
                <el-col :span="4">
                  <span class="title1">出版日期</span>
                </el-col>
                <el-col :span="12">
                  <span>{{ scope.row.publicationDate }}</span>
                </el-col>
              </el-row>
              <!-- 各自那一列里面又分为一行两列 -->
            </el-col>
            <!-- 每一行两列第二列 -->
          </el-row>
          <!-- 每一行 -->
          <br />
          <!-- 最后一行单独放 -->
          <el-row>
            <el-col :offset="2" :span="1">
              <span class="title1" id="title1">简介</span>
            </el-col>
            <el-col :span="12">
              <span class="content">{{ scope.row.content }}</span>
            </el-col>
          </el-row>
          <!-- 最后一行单独放 -->
        </template>
      </el-table-column>
      <el-table-column label="书籍ID" prop="id"> </el-table-column>
      <!-- <el-table-column label="书籍简介" prop="content"> </el-table-column> -->
      <el-table-column label="书籍名称" prop="bookName"> </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row.id)"
            >编辑</el-button
          >
          <el-button
            style="color: #8132d0"
            type="text"
            @click="handleImg(scope.row.id)"
            >添加图片</el-button
          >
          <el-button
            style="color: #5cca43"
            type="text"
            @click="handleClass(scope.row.id)"
            >添加分类</el-button
          >
          &nbsp;
          <el-popconfirm
            title="确认删除？"
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            @confirm="handleDelete(scope.row.id)"
          >
            <el-button slot="reference" type="text" style="color: red"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="[5, 21, 27, 36]"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, sizes"
        :total="page.total"
      >
      </el-pagination>
    </div>
    <!-- ---------------------- -->
    <!-- 添加书籍或者修改书籍的dialog开始 -->
    <el-dialog
      title="书籍信息"
      :visible.sync="dialogVisible1"
      width="45%"
      :before-close="handleClose1"
    >
      <el-form
        :model="book"
        label-width="70px"
        class="demo-ruleForm"
        label-position="right"
      >
        <el-form-item label="书名" prop="bookName">
          <el-input
            v-model="book.bookName"
            placeholder="请输入书籍名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input
            v-model="book.author"
            placeholder="请输入作者名字"
          ></el-input>
        </el-form-item>
        <el-form-item label="书号" prop="bookNo">
          <el-input v-model="book.bookNo" placeholder="请输入书号"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="publish">
          <el-input
            v-model="book.publish"
            placeholder="请输入出版社"
          ></el-input>
        </el-form-item>
        <el-form-item label="出版日期" prop="publicationDate">
          <el-date-picker
            v-model="book.publicationDate"
            type="month"
            :picker-options="pickerOptions"
            placeholder="选择月"
            value-format="yyyy-MM"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="定价" prop="price">
          <el-input-number
            v-model="book.price"
            :precision="2"
            :step="0.01"
            :max="9999"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="简介" prop="content">
          <el-input
            type="textarea"
            resize="none"
            :rows="4"
            placeholder="请输入书籍简介"
            maxlength="300"
            show-word-limit
            v-model="book.content"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <el-button
        style="margin-left: 200px"
        type="primary"
        @click="handleSaveBook"
        >保存信息</el-button
      >
      &nbsp;&nbsp;&nbsp;&nbsp;
      <el-popconfirm
        title="辛苦了这么久真的要重置吗？"
        confirm-button-text="是的"
        cancel-button-text="算了"
        icon="el-icon-info"
        icon-color="red"
        @confirm="handleResetBook"
      >
        <el-button slot="reference" type="info">重置</el-button>
      </el-popconfirm>
    </el-dialog>
    <!-- 添加书籍或者修改书籍的dialog结束 -->
    <!-- ---------------------- -->
    <!-- ---------------------- -->
    <!-- ---------------------- -->
    <!-- 添加分类的dialog开始 -->
    <!-- ---------------------- -->
    <el-dialog
      title="添加分类"
      :visible.sync="dialogVisible2"
      width="30%"
      :before-close="handleClose2"
    >
      <div style="margin-left: 70px">
        <el-select v-model="classAdd" multiple placeholder="请选择分类">
          <el-option
            v-for="item in bookClass"
            :key="item.id"
            :label="item.className"
            :value="item.id"
            :disabled="judgeClassIsDisabled(item.id)"
          >
          </el-option>
        </el-select>
      </div>
      <br /><br /><br /><br /><br />
      <el-button
        style="margin-left: 150px"
        type="primary"
        @click="handleAddClass"
        >确 定</el-button
      >
    </el-dialog>
    <!-- 添加分类的dialog开始 -->
    <!-- ---------------------- -->
    <!-- ---------------------- -->
    <!-- ---------------------- -->
    <!-- 添加图片的dialog的分类开始 -->
    <el-dialog
      title="添加图片"
      :visible.sync="dialogVisible3"
      width="40%"
      :before-close="handleClose3"
    >
      <div
        style="
          display: flex;
          flex-wrap: wrap;
          margin-left: 30px;
          align-items: stretch;
        "
      >
        <div
          v-for="(item, index) in imgAdd"
          :key="index"
          class="image-container"
        >
          <img
            :src="item"
            alt=""
            style="width: 150px; height: 150px; margin: 5px"
          />
          <i class="iconClose el-icon-close" @click="handleRemove(index)"></i>
        </div>
        <el-upload
          style="width: 150px; height: 150px; margin: 5px; flex-shrink: 0"
          ref="submitImg"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :action="loadBookURL"
          list-type="picture-card"
          :show-file-list="false"
          :auto-upload="true"
        >
          <i style="" class="el-icon-plus"></i>
        </el-upload>
      </div>
      <div>
        <el-button
          @click="handleSaveImg"
          type="primary"
          style="margin-left: 200px; margin-top: 20px"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加图片的dialog的分类结束 -->
    <!-- ---------------------- -->
    <!-- ---------------------- -->
    <!-- ---------------------- -->
  </div>
</template>
<script>
import {
  getBooks,
  deleteBook,
  addBook,
  getOneBook,
  getClass,
  getBookClassesById,
} from "../api/bookMG";
import { addBookClasses } from "../api/bookClassesMG";
import { saveImg } from "../api/bookImgMG";
export default {
  name: "BookView",
  data() {
    return {
      pickerOptions: {
        // 定义一个disabledDate函数，用于禁用日期选择器中的某些日期
        disabledDate(time) {
          // 创建一个Date对象，获取当前日期和时间
          const date = new Date(); // 当前日期（具体到秒）

          // 从Date对象中提取当前年份
          const year = date.getFullYear(); // 当前年份

          // 从Date对象中提取当前月份，由于getMonth()方法返回的月份是从0开始的，所以加1
          let month = date.getMonth() + 1; // 当前月份

          // 如果月份是1到9，则在月份前加0，以便后续格式化
          if (month >= 1 && month <= 9) {
            // 1-9月份前加0
            month = "0" + month; // 格式化月份，如9月变为09
          }

          // 将年份和月份拼接成一个字符串，表示当前日期（格式为YYYYMM）
          const currentdate = year.toString() + month.toString(); // 当前日期（格式为字符串）

          // 从传入的time参数中提取年份
          const timeyear = time.getFullYear(); // 传入日期的年份

          // 从传入的time参数中提取月份，并加1
          let timemonth = time.getMonth() + 1; // 传入日期的月份

          // 如果传入的日期月份是1到9，则在月份前加0
          if (timemonth >= 1 && timemonth <= 9) {
            timemonth = "0" + timemonth; // 格式化月份，如9月变为09
          }

          // 将传入的日期的年份和月份拼接成一个字符串，表示该日期（格式为YYYYMM）
          const timedate = timeyear.toString() + timemonth.toString(); // 传入日期的格式化字符串

          // 比较传入的日期（timedate）是否晚于当前日期（currentdate）
          // 如果晚于当前日期，则返回true，表示该日期应该被禁用
          // 否则返回false，表示该日期可用
          return timedate > currentdate; // 返回比较结果，用于禁用或启用日期选择器中的日期
        },
      },
      dialogVisible1: false,
      dialogVisible2: false,
      dialogVisible3: false,
      page: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
        bookName: "",
      },
      bookList: [], //表格展示用的
      book: {}, //添加或更新用的
      bookClass: [], //这里装了所有的书籍分类，
      bookClasses: [], //这里是点击添加分类时查询到的这一本书自己的所有的类别,
      bookId: null, //这里是点击添加图片或者添加分类绑定的书的id值，
      classAdd: [], //这里绑定的是el-select中选中的分类值，
      imgAdd: [], //上传的图片列表，保存的是每个地址
      loadUrl: "http://localhost:8088/loadImg/bookImg?bookId=",
    };
  },
  methods: {
    async handleSaveImg() {
      //将上传到服务器的图片保存到数据库并与点开的书籍相对应
      await saveImg(this.bookId, this.imgAdd).then((res) => {
        if (res.data.code == 200) {
          // console.log(res.data.data);
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "success",
          });
          this.bookId = null;
          this.imgAdd = [];
          this.getBookList();
          this.dialogVisible3 = false;
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
    handleRemove(index) {
      console.log(this.imgAdd);
      //上传后回显，觉得不满意点击右上角的×删除
      this.imgAdd.splice(index, 1);
    },
    handleSuccess(res, file, fileList) {
      //上传成功返回的参数
      //上传图片组件的默认返回参数
      // 假设服务器返回的数据中包含图片的 URL
      if (res.code == 200) {
        this.imgAdd.push(res.data);
        this.$message.success(res.msg);
      } else {
        this.$message.error(res.code + "::" + res.msg);
      }
      console.log(file, fileList);
    },
    beforeUpload(file) {
      console.log(111);
      //上传之前检测一下图片格式和大小
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isPNG = file.type === "image/png";
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPEG && !isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG/JPEG 格式!");
        return false;
      }
      if (file.size > 9 * 1024 * 1024) {
        this.$message.error("上传头像图片大小不能超过 9MB!");
        return false;
      }
      return true;
    },
    handleImg(id) {
      //复制添加图片点击的那本书的id
      this.bookId = id;
      //打开添加图片的dialog
      this.dialogVisible3 = true;
    },
    async handleAddClass() {
      //确认添加分类的事件
      // console.log(this.bookId,this.classAdd)
      if (this.classAdd.length == 0) {
        this.$message({
          showClose: true,
          message: "未选择分类信息",
          type: "error",
        });
        return false;
      }
      await addBookClasses(this.bookId, this.classAdd).then((res) => {
        if (res.data.code == 200) {
          // console.log(res.data.data);
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "success",
          });
          this.bookClasses = [];
          this.bookId = null;
          this.classAdd = [];
          this.getBookList();
          this.dialogVisible2 = false;
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
    //判断这个选项是否禁用，如果id出现在this.bookClasses中就要禁用，
    judgeClassIsDisabled(id) {
      return this.bookClasses.includes(id);
    },
    async handleClass(id) {
      //这里点击添加分类的时候先去获取自己本身已经有的分类信息,然后打开天添加分类的dialog
      // console.log(id)
      this.bookId = id;
      await getBookClassesById(id).then((res) => {
        if (res.data.code == 200) {
          // console.log(res.data.data);
          this.bookClasses = res.data.data;
          this.dialogVisible2 = true;
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
    async getAllClass() {
      //获取所有的分类信息
      await getClass().then((res) => {
        if (res.data.code == 200) {
          // console.log(res.data.data)
          this.bookClass = res.data.data;
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
    async handleEdit(id) {
      //点击编辑获取那本书的详情
      // console.log(id)
      await getOneBook(id).then((res) => {
        if (res.data.code == 200) {
          this.book = res.data.data;
          this.dialogVisible1 = true;
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
    async handleSaveBook() {
      //点击保存书籍信息
      if (
        this.book.bookName == null ||
        this.book.bookName.length < 3 ||
        this.book.bookName.length > 50
      ) {
        this.$message({
          type: "error",
          showClose: true,
          message: "书名不能为空且长度为3-50个字符",
        });
        return;
      }
      if (
        this.book.author == null ||
        this.book.author.length < 2 ||
        this.book.author.length > 30
      ) {
        this.$message({
          type: "error",
          showClose: true,
          message: "作者不能为空且长度为2-30个字符",
        });
        return;
      }
      if (
        this.book.publish == null ||
        this.book.publish.length < 2 ||
        this.book.publish.length > 15
      ) {
        this.$message({
          type: "error",
          showClose: true,
          message: "出版社不能为空且长度为2-15个字符",
        });
        return;
      }
      if (this.book.publicationDate == null) {
        this.$message({
          type: "error",
          showClose: true,
          message: "出版日期不能为空",
        });
        return;
      }
      if (this.book.price == null) {
        this.$message({
          type: "error",
          showClose: true,
          message: "价格不能为空",
        });
        return;
      }
      if (
        this.book.bookNo == null ||
        this.book.bookNo.length < 17 ||
        this.book.bookNo.length > 20
      ) {
        this.$message({
          type: "error",
          showClose: true,
          message: "书号不能为空且长度为17-20个字符",
        });
        return;
      }
      if (this.book.content == null || this.book.content.length < 6) {
        this.$message({
          type: "error",
          showClose: true,
          message: "简介不能为空且长度为6-300个字符",
        });
        return;
      }
      // 以上if语句是在判断输入的条件是否合理
      //当验证正确就会触发这里的方法去请求后端添加图片
      // console.log(this.book)
      await addBook(this.book).then((res) => {
        if (res.data.code == 200) {
          this.book = {};
          this.getBookList();
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "success",
          });
          this.dialogVisible1 = false;
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
    handleResetBook() {
      //编辑或添加图书的时候重置信息
      this.book = {};
    },
    handleClose1(done) {
      // 关闭dialog111111
      this.book = {};
      done();
    },
    handleClose2(done) {
      // 关闭dialog2222222
      this.bookClasses = []; //清空某本书的已有的分类信息
      this.bookId = null; //清空点击添加图片或添加分类时选中的某本书的id
      this.classAdd = []; //清空选中的书的类的id
      done();
    },
    handleClose3(done) {
      // 关闭dialog3333333
      this.bookId = null; //清空点击添加图片或添加分类时选中的某本书的id
      this.imgAdd = []; //清空上传的选中的书的图片地址
      done();
    },
    async handleDelete(id) {
      // 删除书籍
      await deleteBook(id).then((res) => {
        if (res.data.code == 200) {
          this.getBookList();
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "success",
          });
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
    reset() {
      //点击重置
      this.page.currentPage = 1;
      this.page.bookName = "";
      //重新获取列表数据
      this.getBookList();
    },
    search() {
      //点击搜索
      this.page.currentPage = 1;
      //重新获取列表数据
      this.getBookList();
    },
    handleSizeChange(pageSize) {
      //改变每页尺寸触发事件
      this.page.pageSize = pageSize;
      //重新获取列表数据
      this.getBookList();
    },
    handleCurrentChange(currentPage) {
      //改变当前页也会触发事件
      this.page.currentPage = currentPage;
      //重新获取列表数据
      this.getBookList();
    },
    async getBookList() {
      await getBooks(this.page).then((res) => {
        if (res.data.code == 200) {
          this.page.total = res.data.data.total;
          this.bookList = res.data.data.list;
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
  },
  computed: {
    loadBookURL() {
      if (this.bookId == null) {
        return "#";
      }
      return this.loadUrl + this.bookId;
    },
  },
  mounted() {
    this.getBookList();
    this.getAllClass();
  },
};
</script>
<style lang="scss" scoped>
.title1 {
  color: #99a9bf;
}
.content,
#title1 {
  line-height: 40px;
}

// 设置图片叉叉图标的位置开始
.image-container {
  position: relative; /* 设置相对定位 */
  transition: transform 0.3s ease; /* 平滑过渡效果 */
}
.image-container:hover {
  color: red;
  transform: scale(1.1); /* 鼠标悬停时放大1.5倍 */
}
.iconClose {
  position: absolute; /* 设置绝对定位 */
  top: 10px; /* 距离容器顶部的位置 */
  right: 10px; /* 距离容器右侧的位置 */
  cursor: pointer; /* 鼠标悬停时显示为手型 */
}
// 设置图片叉叉图标的位置结束
</style>